<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>34-正则表达式</title>
  
    
      <meta 
        property="og:title" 
        content="34-正则表达式">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/34-%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2004-03-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%AE%80%E4%BB%8B"><span class="toc-text">正则表达式简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">创建正则表达式的对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">方式一：使用构造函数创建正则表达式的对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8%E5%AD%97%E9%9D%A2%E9%87%8F%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">方式二：使用字面量创建正则表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A5%E4%B8%8A%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="toc-text">以上两种方式的对比</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%9D%91%E6%8C%87%E5%8D%97%EF%BC%9A%E5%85%A8%E5%B1%80%E5%8C%B9%E9%85%8D-g-%E6%85%8E%E7%94%A8test-%E6%96%B9%E6%B3%95"><span class="toc-text">避坑指南：全局匹配 g 慎用test()方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%AD%E6%B3%95"><span class="toc-text">正则表达式的简单语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E6%98%AF%E5%90%A6%E5%8C%85%E5%90%AB-a%E6%88%96b"><span class="toc-text">检查一个字符串中是否包含 a或b</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E6%88%96"><span class="toc-text">[]表示：或</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E9%99%A4%E4%BA%86"><span class="toc-text">[^ ] 表示：除了</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84-String-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-text">支持正则表达式的 String 对象的方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#split"><span class="toc-text">split()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#search"><span class="toc-text">search()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#match"><span class="toc-text">match()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#replace"><span class="toc-text">replace()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E4%B8%BE%E4%BE%8B"><span class="toc-text">常见正则表达式举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E6%98%AF%E4%B8%80%E4%B8%AA%E5%90%88%E6%B3%95%E6%89%8B%E6%9C%BA%E5%8F%B7"><span class="toc-text">检查一个字符串是否是一个合法手机号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%BB%E6%8E%89%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%BC%80%E5%A4%B4%E5%92%8C%E7%BB%93%E5%B0%BE%E7%9A%84%E7%A9%BA%E6%A0%BC"><span class="toc-text">去掉字符串开头和结尾的空格</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E4%B8%BA%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6"><span class="toc-text">判断字符串是否为电子邮件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      34-正则表达式
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2004-02-29T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2004-03-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80/" 
          class="post-meta-link">
          JS基础
        </a>
      
    
    
      <span class="dot"></span>
      <span>2.8k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80/" 
            class="post-meta-link">
            JS基础
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="正则表达式简介"><a href="#正则表达式简介" class="headerlink" title="正则表达式简介"></a>正则表达式简介</h2><p><strong>定义</strong>：正则表达式用于定义一些字符串的规则。</p>
<p><strong>作用</strong>：计算机可以根据正则表达式，来检查一个字符串是否符合指定的规则；或者将字符串中符合规则的内容提取出来。</p>
<p>如果你想查看正则更多的内容，可以查阅官方文档关于 RegExp 这个内置对象的用法。</p>
<h2 id="创建正则表达式的对象"><a href="#创建正则表达式的对象" class="headerlink" title="创建正则表达式的对象"></a>创建正则表达式的对象</h2><h3 id="方式一：使用构造函数创建正则表达式的对象"><a href="#方式一：使用构造函数创建正则表达式的对象" class="headerlink" title="方式一：使用构造函数创建正则表达式的对象"></a>方式一：使用构造函数创建正则表达式的对象</h3><p>语法：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> 变量 = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot;正则表达式&quot;</span>); <span class="comment">// 注意，参数是字符串</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> 变量 = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot;正则表达式&quot;</span>, <span class="string">&quot;匹配模式&quot;</span>); <span class="comment">// 注意，两个参数都是字符串</span></span><br></pre>

<p>备注：<code>RegExp</code>的意思是 <strong>Regular expression</strong>。使用typeof检查正则对象，会返回object。</p>
<p>上面的语法中，既可以传一个参数，也可以传两个参数。</p>
<p>创建了正则表达式的对象后，该怎么使用呢？大致分为两个步骤：</p>
<ul>
<li><p>（1）创建正则表达式的对象 reg。</p>
</li>
<li><p>（2）使用 reg 的test() 方法，判断指定字符串是否符合规则。</p>
</li>
</ul>
<p><strong>正则表达式的<code>test()</code>方法</strong>：【重要】</p>
<pre class="highlight"><span class="line">myReg.<span class="title function_">test</span>(str); <span class="comment">// 判断字符串 str 是否符合 指定的 myReg 这个正则表达式的规则</span></span><br></pre>

<p>解释：使用<code>test()</code>这个方法可以用来检查一个字符串是否符合正则表达式的规则，<strong>如果符合则返回true，否则返回false</strong>。</p>
<p>我们来看看下面的例子。</p>
<p><strong>1、传一个参数时</strong>：</p>
<p>构造函数 RegExp 中，可以只传一个参数。</p>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot;a&quot;</span>); <span class="comment">// 定义一个正则表达式：检查一个字符串中是否含有 a</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str1 = <span class="string">&quot;qianguyihao&quot;</span>;</span><br><span class="line"><span class="keyword">var</span> str2 = <span class="string">&quot;smyh&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过 test()方法，判断字符串是否符合 上面定义的 reg 规则</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str1)); <span class="comment">// 打印结果：true</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str2)); <span class="comment">// 打印结果：false</span></span><br><span class="line"></span><br></pre>

<p>注意，上面的例子中，我们是先定义了一个正则表达式的规则，然后通过正则表达式的<code>test()</code>方法来判断字符串是否符合之前定义的规则。</p>
<p><strong>2、传两个参数时</strong>：匹配模式 【重要】</p>
<p>构造函数 RegExp 中，也可以传两个参数。我们可以传递一个<strong>匹配模式</strong>作为第二个参数。这个参数可以是：</p>
<ul>
<li><p><code>i</code> 忽略大小写。这里的 i 指的是 ignore。</p>
</li>
<li><p><code>g</code> 全局匹配模式。这里的 g 指的是 global。</p>
</li>
</ul>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&#x27;A&#x27;</span>, <span class="string">&#x27;i&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> str = <span class="string">&#x27;qiangu&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// 打印结果：true</span></span><br></pre>

<h3 id="方式二：使用字面量创建正则表达式"><a href="#方式二：使用字面量创建正则表达式" class="headerlink" title="方式二：使用字面量创建正则表达式"></a>方式二：使用字面量创建正则表达式</h3><p>我们可以使用字面量来创建正则表达式。</p>
<p>语法：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> 变量 = <span class="regexp">/正则表达式/</span>;  <span class="comment">// 注意，这个语法里没有引号</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> 变量 = <span class="regexp">/正则表达式/</span>匹配模式;  <span class="comment">// 注意，这个语法里没有引号</span></span><br></pre>

<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/A/i</span>; <span class="comment">// 定义正则表达式的规则：检查一个字符串中是否含有 a。忽略大小写。</span></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">&quot;qiangu&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="keyword">typeof</span> reg);  <span class="comment">// 打印结果：object</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// 打印结果：true</span></span><br></pre>

<h3 id="以上两种方式的对比"><a href="#以上两种方式的对比" class="headerlink" title="以上两种方式的对比"></a>以上两种方式的对比</h3><ul>
<li><p>方式一：使用构造函数创建时，更加灵活，因为参数中还可以传递变量。</p>
</li>
<li><p>方式二：使用字面量的方式创建，更加简单。</p>
</li>
</ul>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot;a&quot;</span>, <span class="string">&quot;i&quot;</span>); <span class="comment">// 方式一</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/a/i</span>; <span class="comment">// 方式二</span></span><br></pre>

<p>上面这两行代码的作用是等价的。</p>
<h3 id="避坑指南：全局匹配-g-慎用test-方法"><a href="#避坑指南：全局匹配-g-慎用test-方法" class="headerlink" title="避坑指南：全局匹配 g 慎用test()方法"></a>避坑指南：全局匹配 g 慎用test()方法</h3><p>对于非全局匹配的正则表达式，<code>test()</code>只会检测<strong>是否存在某个目标字符串</strong>（只要存在就为 true），多次检测的结果都相同。例如：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> reg = <span class="regexp">/test/</span>;</span><br><span class="line"><span class="keyword">const</span> str = <span class="string">&#x27;_test_test&#x27;</span>;</span><br><span class="line"></span><br><span class="line">reg.<span class="title function_">test</span>(str) <span class="comment">// true</span></span><br><span class="line">reg.<span class="title function_">test</span>(str) <span class="comment">// true</span></span><br><span class="line">reg.<span class="title function_">test</span>(str) <span class="comment">// true</span></span><br></pre>

<p>重点来了。</p>
<p>当设置全局标志 <code>/g</code> 时，一旦字符串中还存在匹配，test() 方法都将返回 true，同时匹配成功后将把 <code>lastIndex</code> 属性的值<strong>设置为上次匹配成功结果之后的第一个字符所在的位置</strong>，下次匹配将从 <code>lastIndex</code> 指示的位置开始；匹配不成功时返回 false，同时将 lastIndex 属性的值重置为 0。</p>
<p>举例：（很重要的例子，看仔细）</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> reg = <span class="regexp">/test/g</span>;</span><br><span class="line"><span class="keyword">const</span> str = <span class="string">&#x27;_test_test&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// true</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="property">lastIndex</span>); <span class="comment">// 5</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// true</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="property">lastIndex</span>); <span class="comment">// 10</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// false</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="property">lastIndex</span>); <span class="comment">// 0</span></span><br></pre>

<p><strong>总结</strong>：</p>
<p>全局匹配模式<code>g</code>一般用于 <code>exec()</code>、<code>match()</code>、<code>replace()</code>等方法。</p>
<p>全局匹配模式<code>g</code>如果用于test()方法会有问题。因为g模式会生成一个<code>lastindex</code>参数来存储匹配最后一次的位置。</p>
<p>参考链接：</p>
<ul>
<li><p><a target="_blank" rel="noopener" href="https://juejin.im/post/5de9bd5fe51d45582c27b6f3">JS正则表达式全局匹配的那些坑</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Leolu007/article/details/8576490">javascript正则全局匹配g慎用test方法</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://github.com/qianguyihao/Web/issues/69">issues</a></p>
</li>
</ul>
<h2 id="正则表达式的简单语法"><a href="#正则表达式的简单语法" class="headerlink" title="正则表达式的简单语法"></a>正则表达式的简单语法</h2><h3 id="检查一个字符串中是否包含-a或b"><a href="#检查一个字符串中是否包含-a或b" class="headerlink" title="检查一个字符串中是否包含 a或b"></a>检查一个字符串中是否包含 a或b</h3><p><strong>写法1</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/a|b/</span>;</span><br></pre>

<p>解释：使用 <code>|</code> 表示<code>或</code>的意思。</p>
<p><strong>写法2</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/[ab]/</span>;  <span class="comment">// 跟上面的那行语法，是等价的</span></span><br></pre>

<p>解释：这里的<code>[]</code>也是表示<code>或</code>的意思。</p>
<p><code>[]</code>这个符号在正则还是比较常用的。我们接下来看几个例子。</p>
<h3 id="表示：或"><a href="#表示：或" class="headerlink" title="[]表示：或"></a>[]表示：或</h3><p>一些规则：</p>
<ul>
<li><p><code>/[ab]/</code> 等价于 <code>/a|b/</code>：检查一个字符串中是否包含 <strong>a或b</strong></p>
</li>
<li><p><code>/[a-z]/</code>：检查一个字符串那种是否包含<strong>任意小写字母</strong></p>
</li>
<li><p><code>/[A-Z]/</code>：任意大写字母</p>
</li>
<li><p><code>/[A-z]/</code>：任意字母</p>
</li>
<li><p><code>/[0-9]/</code>：任意数字</p>
</li>
<li><p><code>/a[bde]c/</code>：检查一个字符串中是否包含 abc 或 adc 或 aec</p>
</li>
</ul>
<h3 id="表示：除了"><a href="#表示：除了" class="headerlink" title="[^ ] 表示：除了"></a>[^ ] 表示：除了</h3><p>举例1：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/[^ab]/</span>; <span class="comment">// 规则：字符串中，除了a、b之外，还有没有其他的字符内容？</span></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">&quot;acb&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str)); <span class="comment">// 打印结果：true</span></span><br></pre>

<p>举例2：（可以用来验证某字符串是否为 纯数字）</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/[^0-9]/</span>;  <span class="comment">// 规则：字符串中，除了数字之外，还有没有其他的内容？</span></span><br><span class="line"><span class="keyword">var</span> str1 = <span class="string">&quot;1991&quot;</span>;</span><br><span class="line"><span class="keyword">var</span> str2 = <span class="string">&quot;199a1&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str1)); <span class="comment">// 打印结果：false （如果字符串是 纯数字，则返回 false）</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(reg.<span class="title function_">test</span>(str2)); <span class="comment">// 打印结果：true</span></span><br></pre>

<h2 id="支持正则表达式的-String-对象的方法"><a href="#支持正则表达式的-String-对象的方法" class="headerlink" title="支持正则表达式的 String 对象的方法"></a>支持正则表达式的 String 对象的方法</h2><p> String对象的如下方法，是支持正则表达式的：</p>
<table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
<th align="left">备注</th>
</tr>
</thead>
<tbody><tr>
<td align="left">split()</td>
<td align="left">将字符串拆分成数组</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">search()</td>
<td align="left">搜索字符串中是否含有指定内容，返回索引 index</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">match()</td>
<td align="left">根据正则表达式，从一个字符串中将符合条件的内容提取出来</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">replace()</td>
<td align="left">将字符串中的指定内容，替换为新的内容并返回</td>
<td align="left"></td>
</tr>
</tbody></table>
<p>下面来分别介绍和举例。</p>
<h3 id="split"><a href="#split" class="headerlink" title="split()"></a>split()</h3><p><code>split()</code>：将一个字符串拆分成一个数组。可以接受一个正则表达式作为参数。</p>
<p>备注：关于<code>split()</code>更详细的用法，可以看之前的关于《内置对象：String》这篇文章。</p>
<p><strong>正则相关的举例</strong>：根据任意字母，将字符串拆分成数组。</p>
<p>代码实现：（通过正则）</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> str = <span class="string">&quot;1a2b3c4d5e6f7g&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> result = str.<span class="title function_">split</span>(<span class="regexp">/[A-z]/</span>); <span class="comment">// 参数是一个正则表达式：表示所有字母</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(result);</span><br></pre>

<p>打印结果：</p>
<pre class="highlight"><span class="line"><span class="punctuation">[</span><span class="string">&quot;1&quot;</span><span class="punctuation">,</span> <span class="string">&quot;2&quot;</span><span class="punctuation">,</span> <span class="string">&quot;3&quot;</span><span class="punctuation">,</span> <span class="string">&quot;4&quot;</span><span class="punctuation">,</span> <span class="string">&quot;5&quot;</span><span class="punctuation">,</span> <span class="string">&quot;6&quot;</span><span class="punctuation">,</span> <span class="string">&quot;7&quot;</span><span class="punctuation">,</span> <span class="string">&quot;&quot;</span><span class="punctuation">]</span></span><br></pre>

<h3 id="search"><a href="#search" class="headerlink" title="search()"></a>search()</h3><p><code>search()</code>：搜索字符串中是否含有指定内容。如果搜索到指定内容，则会返回第一次出现的索引；否则返回-1。</p>
<p><code>search()</code>方法可以接受一个正则表达式作为参数，然后会根据正则表达式去检索字符串。<code>serach()</code>只会查找第一个，即使设置全局匹配也没用。</p>
<p><strong>举例</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> str = <span class="string">&quot;hello abc hello aec afc&quot;</span>;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 搜索字符串中是否含有abc 或 aec 或 afc</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">result = str.<span class="title function_">search</span>(<span class="regexp">/a[bef]c/</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(result); <span class="comment">// 打印结果：6</span></span><br></pre>

<h3 id="match"><a href="#match" class="headerlink" title="match()"></a>match()</h3><p><code>match()</code>：根据正则表达式，从一个字符串中将符合条件的内容提取出来，封装到一个数组中返回（即使只查询到一个结果）。</p>
<p><strong>注意</strong>：默认情况下，<code>match()</code>方法只会找到<strong>第一个</strong>符合要求的内容，找到以后就停止检索。我们可以设置正则表达式为<strong>全局匹配</strong>模式，这样就会匹配到所有的内容，并以<strong>数组</strong>的形式返回。</p>
<p>另外，我们可以为一个正则表达式设置多个匹配模式，且匹配模式的顺序无所谓。</p>
<p><strong>代码举例</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> str = <span class="string">&quot;1a2a3a4a5e6f7A8B9C&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> result1 = str.<span class="title function_">match</span>(<span class="regexp">/[a-z]/</span>);   <span class="comment">// 找到符合要求的第一个内容，然后返回</span></span><br><span class="line"><span class="keyword">var</span> result2 = str.<span class="title function_">match</span>(<span class="regexp">/[a-z]/g</span>);  <span class="comment">// 设置为“全局匹配”模式，匹配字符串中 所有的小写字母</span></span><br><span class="line"><span class="keyword">var</span> result3 = str.<span class="title function_">match</span>(<span class="regexp">/[a-z]/gi</span>); <span class="comment">// 设置多个匹配模式，匹配字符串中 所有的字母（忽略大小写）</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(result1); <span class="comment">// 打印结果：[&quot;a&quot;]</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(result2); <span class="comment">// 打印结果：[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;e&quot;, &quot;f&quot;]</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(result3); <span class="comment">// 打印结果：[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;e&quot;, &quot;f&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;]</span></span><br></pre>

<p><strong>总结</strong>：</p>
<p>match()这个方法还是很实用的，可以在一个很长的字符串中，提取出<strong>有规则</strong>的内容。这不就是爬虫的时候经常会遇到的场景么？</p>
<h3 id="replace"><a href="#replace" class="headerlink" title="replace()"></a>replace()</h3><p><code>replace()</code>：将字符串中的指定内容，替换为新的内容并返回。不会修改原字符串。</p>
<p>语法：</p>
<pre class="highlight"><span class="line">新的字符串 = str.<span class="title function_">replace</span>(被替换的内容，新的内容);</span><br></pre>

<p>参数解释：</p>
<ul>
<li><p>被替换的内容：可以接受一个正则表达式作为参数。</p>
</li>
<li><p>新的内容：默认只会替换第一个。如果需要替换全部符合条件的内容，可以设置正则表达式为<strong>全局匹配</strong>模式。</p>
</li>
</ul>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="comment">//replace()方法：替换</span></span><br><span class="line"><span class="keyword">var</span> str2 = <span class="string">&quot;Today is fine day,today is fine day !!!&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(str2);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(str2.<span class="title function_">replace</span>(<span class="string">&quot;today&quot;</span>,<span class="string">&quot;tomorrow&quot;</span>));  <span class="comment">//只能替换第一个today</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(str2.<span class="title function_">replace</span>(<span class="regexp">/today/gi</span>,<span class="string">&quot;tomorrow&quot;</span>)); <span class="comment">//这里用到了正则，且为“全局匹配”模式，才能替换所有的today</span></span><br></pre>

<h2 id="常见正则表达式举例"><a href="#常见正则表达式举例" class="headerlink" title="常见正则表达式举例"></a>常见正则表达式举例</h2><h3 id="检查一个字符串是否是一个合法手机号"><a href="#检查一个字符串是否是一个合法手机号" class="headerlink" title="检查一个字符串是否是一个合法手机号"></a>检查一个字符串是否是一个合法手机号</h3><p>手机号的规则：</p>
<ul>
<li><p>以1开头（<code>^1</code> 表示1开头 , <code>[^1]</code>表示非1或除了1）</p>
</li>
<li><p>第二位是3~9之间任意数字</p>
</li>
<li><p>三位以后任意9位数字</p>
</li>
</ul>
<p>正则实现：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> phoneStr = <span class="string">&quot;13067890123&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> phoneReg = <span class="regexp">/^1[3-9][0-9]&#123;9&#125;$/</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(phoneReg.<span class="title function_">test</span>(phoneStr));</span><br></pre>

<p><strong>备注</strong>：如果在正则表达式中同时使用<code>^</code>和<code>$</code>符号，则要求字符串必须完全符合正则表达式。</p>
<h3 id="去掉字符串开头和结尾的空格"><a href="#去掉字符串开头和结尾的空格" class="headerlink" title="去掉字符串开头和结尾的空格"></a>去掉字符串开头和结尾的空格</h3><p>正则实现：</p>
<pre class="highlight"><span class="line">str = str.<span class="title function_">replace</span>(<span class="regexp">/^\s*|\s*$/g</span>,<span class="string">&quot;&quot;</span>);</span><br></pre>

<p>解释如下：</p>
<pre class="highlight"><span class="line">str = str.<span class="title function_">replace</span>(<span class="regexp">/^\s*/</span>, <span class="string">&quot;&quot;</span>); <span class="comment">//去除开头的空格</span></span><br><span class="line"></span><br><span class="line">str = str.<span class="title function_">replace</span>(<span class="regexp">/\s*$/</span>, <span class="string">&quot;&quot;</span>); <span class="comment">//去除结尾的空格</span></span><br></pre>

<h3 id="判断字符串是否为电子邮件"><a href="#判断字符串是否为电子邮件" class="headerlink" title="判断字符串是否为电子邮件"></a>判断字符串是否为电子邮件</h3><p>正则实现：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> emailReg = <span class="regexp">/^\w&#123;3,&#125;(\.\w+)*@[A-z0-9]+(\.[A-z]&#123;2,5&#125;)&#123;1,2&#125;$/</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> email = <span class="string">&quot;abchello@163.com&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(emailReg.<span class="title function_">test</span>(email));</span><br></pre>


<h2 id="我的公众号"><a href="#我的公众号" class="headerlink" title="我的公众号"></a>我的公众号</h2><p>想学习<strong>更多技能</strong>？不妨关注我的微信公众号：<strong>千古壹号</strong>（id：<code>qianguyihao</code>）。</p>
<p>扫一扫，你将发现另一个全新的世界，而这将是一场美丽的意外：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20190101.png" class="lozad post-image"src="http://img.smyhvae.com/20190101.png"></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/34-%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">
            https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/34-%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/35-%E4%BA%8B%E4%BB%B6%E7%AE%80%E4%BB%8B/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">35-事件简介 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/36-DOM%E7%AE%80%E4%BB%8B%E5%92%8CDOM%E6%93%8D%E4%BD%9C/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">36-DOM简介和DOM操作 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%AE%80%E4%BB%8B"><span class="toc-text">正则表达式简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">创建正则表达式的对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">方式一：使用构造函数创建正则表达式的对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8%E5%AD%97%E9%9D%A2%E9%87%8F%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">方式二：使用字面量创建正则表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A5%E4%B8%8A%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="toc-text">以上两种方式的对比</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%9D%91%E6%8C%87%E5%8D%97%EF%BC%9A%E5%85%A8%E5%B1%80%E5%8C%B9%E9%85%8D-g-%E6%85%8E%E7%94%A8test-%E6%96%B9%E6%B3%95"><span class="toc-text">避坑指南：全局匹配 g 慎用test()方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%AD%E6%B3%95"><span class="toc-text">正则表达式的简单语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E6%98%AF%E5%90%A6%E5%8C%85%E5%90%AB-a%E6%88%96b"><span class="toc-text">检查一个字符串中是否包含 a或b</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E6%88%96"><span class="toc-text">[]表示：或</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E9%99%A4%E4%BA%86"><span class="toc-text">[^ ] 表示：除了</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84-String-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-text">支持正则表达式的 String 对象的方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#split"><span class="toc-text">split()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#search"><span class="toc-text">search()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#match"><span class="toc-text">match()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#replace"><span class="toc-text">replace()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E4%B8%BE%E4%BE%8B"><span class="toc-text">常见正则表达式举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E6%98%AF%E4%B8%80%E4%B8%AA%E5%90%88%E6%B3%95%E6%89%8B%E6%9C%BA%E5%8F%B7"><span class="toc-text">检查一个字符串是否是一个合法手机号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%BB%E6%8E%89%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%BC%80%E5%A4%B4%E5%92%8C%E7%BB%93%E5%B0%BE%E7%9A%84%E7%A9%BA%E6%A0%BC"><span class="toc-text">去掉字符串开头和结尾的空格</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E4%B8%BA%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6"><span class="toc-text">判断字符串是否为电子邮件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%AE%80%E4%BB%8B"><span class="toc-text">正则表达式简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">创建正则表达式的对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-text">方式一：使用构造函数创建正则表达式的对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8%E5%AD%97%E9%9D%A2%E9%87%8F%E5%88%9B%E5%BB%BA%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">方式二：使用字面量创建正则表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A5%E4%B8%8A%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="toc-text">以上两种方式的对比</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%9D%91%E6%8C%87%E5%8D%97%EF%BC%9A%E5%85%A8%E5%B1%80%E5%8C%B9%E9%85%8D-g-%E6%85%8E%E7%94%A8test-%E6%96%B9%E6%B3%95"><span class="toc-text">避坑指南：全局匹配 g 慎用test()方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%AD%E6%B3%95"><span class="toc-text">正则表达式的简单语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E6%98%AF%E5%90%A6%E5%8C%85%E5%90%AB-a%E6%88%96b"><span class="toc-text">检查一个字符串中是否包含 a或b</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E6%88%96"><span class="toc-text">[]表示：或</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%A4%BA%EF%BC%9A%E9%99%A4%E4%BA%86"><span class="toc-text">[^ ] 表示：除了</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84-String-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-text">支持正则表达式的 String 对象的方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#split"><span class="toc-text">split()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#search"><span class="toc-text">search()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#match"><span class="toc-text">match()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#replace"><span class="toc-text">replace()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E4%B8%BE%E4%BE%8B"><span class="toc-text">常见正则表达式举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E6%98%AF%E4%B8%80%E4%B8%AA%E5%90%88%E6%B3%95%E6%89%8B%E6%9C%BA%E5%8F%B7"><span class="toc-text">检查一个字符串是否是一个合法手机号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%BB%E6%8E%89%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%BC%80%E5%A4%B4%E5%92%8C%E7%BB%93%E5%B0%BE%E7%9A%84%E7%A9%BA%E6%A0%BC"><span class="toc-text">去掉字符串开头和结尾的空格</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E4%B8%BA%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6"><span class="toc-text">判断字符串是否为电子邮件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
